package com.anyou.mall.use.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.anyou.common.core.domain.ApiResult;
import com.anyou.common.utils.DateUtils;
import com.anyou.common.utils.StringUtils;
import com.anyou.mall.index.param.OrderNumParam;
import com.anyou.mall.index.param.UserNumParam;
import com.anyou.mall.index.vo.*;
import com.anyou.mall.order.domain.OrdOrder;
import com.anyou.mall.order.mapper.OrdOrderMapper;
import com.anyou.mall.sho.domain.CarPartsShopAudit;
import com.anyou.mall.sho.service.ICarPartsShopAuditService;
import com.anyou.mall.use.domain.UserAddress;
import com.anyou.mall.use.mapper.UserAddressMapper;
import com.anyou.mall.use.param.NoticeListParam;
import com.anyou.mall.use.param.UserChildParam;
import com.anyou.mall.use.param.UserIntegralParam;
import com.anyou.mall.use.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.anyou.mall.use.mapper.UserMapper;
import com.anyou.mall.use.domain.User;
import com.anyou.mall.use.service.IUserService;
import org.springframework.util.CollectionUtils;

/**
 * 用户管理Service业务层处理
 *
 * @author gaochaohao
 * @date 2022-03-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService
{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICarPartsShopAuditService carPartsShopAuditService;


    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private OrdOrderMapper ordOrderMapper;

    /**
     * 查询用户管理
     *
     * @param userId 用户管理主键
     * @return 用户管理
     */
    @Override
    public UserQueryVo selectUserByUserId(Long userId)
    {
        UserQueryVo userQueryVo = new UserQueryVo();
        User user = userMapper.selectUserByUserId(userId);
        if (user == null) {
            return null;
        }
        BeanUtils.copyProperties(user,userQueryVo);
        //根据用户id查询用户的收货地址
        List<UserQueryAddressesVo> addressesVoList = new ArrayList<>();
        UserQueryAddressesVo userQueryAddressesVo = new UserQueryAddressesVo();
        List<UserAddress> userAddresses = userAddressMapper.selectUserAddressListByUserId(userId);
        if (userAddresses != null) {
            for (UserAddress userAddress : userAddresses) {
                BeanUtils.copyProperties(userAddress,userQueryAddressesVo);
                addressesVoList.add(userQueryAddressesVo);
            }
            userQueryVo.setUserAddresses(addressesVoList);
        }


        return userQueryVo;
    }

    /**
     * 查询用户管理列表
     *
     * @param user 用户管理
     * @return 用户管理
     */
    @Override
    public List<User> selectUserList(User user)
    {
        return userMapper.selectUserList(user);
    }

    @Override
    public List<IntegralRecordVo> userIntegralList(UserIntegralParam param) {
        return userMapper.userIntegralList(param);
    }

    /**
     * 新增用户管理
     *
     * @param user 用户管理
     * @return 结果
     */
    @Override
    public int insertUser(User user)
    {
        user.setCreateTime(DateUtils.getNowDate());
        return userMapper.insertUser(user);
    }

    /**
     * 修改用户管理
     *
     * @param user 用户管理
     * @return 结果
     */
    @Override
    public int updateUser(User user)
    {
        user.setUpdateTime(DateUtils.getNowDate());
        return userMapper.updateUser(user);
    }

    /**
     * 批量删除用户管理
     *
     * @param userIds 需要删除的用户管理主键
     * @return 结果
     */
    @Override
    public int deleteUserByUserIds(Long[] userIds)
    {
        return userMapper.deleteUserByUserIds(userIds);
    }

    /**
     * 删除用户管理信息
     *
     * @param userId 用户管理主键
     * @return 结果
     */
    @Override
    public int deleteUserByUserId(Long userId)
    {
        return userMapper.deleteUserByUserId(userId);
    }

    @Override
    public ApiResult updateUserStatus(Long userId) {
        User user = userMapper.selectUserByUserId(userId);
        if (user != null) {
            if ("1".equals(user.getAccountStatus())) {
                user.setAccountStatus("0");
            } else {
                user.setAccountStatus("1");
            }
            return ApiResult.success(userMapper.updateUser(user));
        } else {
            return ApiResult.error("修改失败");
        }
    }

    @Override
    public List<User> selectNoticeUserList(NoticeListParam noticeListParam) {
        List<Long> userIds = new ArrayList<>();



//        //当车品牌和车系不为空时查询对应下的id数组
//        QueryWrapper<UserCar> userCarQueryWrapper = new QueryWrapper<>();
//        if (noticeListParam.getCarBrandIds() != null) {
//            userCarQueryWrapper.in("car_brand_id",noticeListParam.getCarBrandIds());
//        }
//        if (noticeListParam.getCarSeriesIds() != null) {
//            userCarQueryWrapper.in("car_series_id",noticeListParam.getCarSeriesIds());
//        }
//        List<UserCar> userCars = userCarService.list(userCarQueryWrapper);
//        if (userCars != null) {
//            List<Boolean> booleans = userCars.stream().map(userCar -> {
//                return userIds.add(userCar.getUserId());
//            }).collect(Collectors.toList());
//        }

        //其他条件不为空时查询汽配商和维修厂对应的数组
        QueryWrapper<CarPartsShopAudit> carPartsShopAuditQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(noticeListParam.getEnterpriseTypeIds())) {
            carPartsShopAuditQueryWrapper.in("enterprise_type_id",noticeListParam.getEnterpriseTypeIds());
        }
        if (StringUtils.isNotEmpty(noticeListParam.getIdentityTypeIds())) {
            carPartsShopAuditQueryWrapper.in("identity_type_id",noticeListParam.getIdentityTypeIds());
        }
        if (StringUtils.isNotEmpty(noticeListParam.getProvince())) {
            carPartsShopAuditQueryWrapper.eq("province",noticeListParam.getProvince());
        }
        if (StringUtils.isNotEmpty(noticeListParam.getCity())) {
            carPartsShopAuditQueryWrapper.eq("city",noticeListParam.getCity());
        }
        if (StringUtils.isNotEmpty(noticeListParam.getCarPartsCityIds())) {
            carPartsShopAuditQueryWrapper.in("car_parts_city_id",noticeListParam.getCarPartsCityIds());
        }
        if (StringUtils.isNotEmpty(noticeListParam.getCarPartsShopBondStatus())) {
            carPartsShopAuditQueryWrapper.eq("bond_status",noticeListParam.getCarPartsShopBondStatus());
        }
        List<CarPartsShopAudit> carPartsShopAuditList = carPartsShopAuditService.list(carPartsShopAuditQueryWrapper);
        if (!CollectionUtils.isEmpty(carPartsShopAuditList)) {
            carPartsShopAuditList.forEach(carPartsShopAudit -> {
                userIds.add(carPartsShopAudit.getUserId());
            });
//            carPartsShopAuditList.stream().map(carPartsShopAudit -> {
//                return userIds.add(carPartsShopAudit.getUserId());
//            }).collect(Collectors.toList());
        }
        List<User> userList1 = userService.list();
        if (userList1 != null) {
            userList1.forEach(user -> {
                if (!userIds.contains(user.getUserId())) {
                    userIds.add(user.getUserId());
                }
            });
        }

        // 创建
        List<User> userList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userIds)){
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.in("user_id",userIds);
            userList = userService.list(wrapper);
            userIds.clear();
        }
        return userList;
    }

    @Override
    public List<UserNum> getUserNumByDate(UserNumParam userNumParam) {
        List<UserNum> list= userMapper.getUserNumByDate(userNumParam);
        return list;
    }

    @Override
    public OrderAnalysis getOrderAnalysis(UserNumParam userNumParam) {

        //总订单数
        Integer orderTotal = ordOrderMapper.selectCount(new LambdaQueryWrapper<OrdOrder>()
                .eq(OrdOrder::getDelFlag, "0")
                .between(StringUtils.isNotEmpty(userNumParam.getStartTime())&&StringUtils.isNotEmpty(userNumParam.getEndTime())
                        ,OrdOrder::getCreateTime,userNumParam.getStartTime(),userNumParam.getEndTime()));
        //安邮普通配送订单数量
        Integer commonNum = ordOrderMapper.selectCount(new LambdaQueryWrapper<OrdOrder>()
                .eq(OrdOrder::getDelFlag, "0")
                .eq(OrdOrder::getReceivingType,"1")
                .eq(OrdOrder::getDeliveryMode,"1")
                .eq(OrdOrder::getIsUrgentDelivery,"0")
                .between(StringUtils.isNotEmpty(userNumParam.getStartTime())&&StringUtils.isNotEmpty(userNumParam.getEndTime())
                        ,OrdOrder::getCreateTime,userNumParam.getStartTime(),userNumParam.getEndTime()));
        //安邮加急配送订单数量
        Integer jiaJiNum = ordOrderMapper.selectCount(new LambdaQueryWrapper<OrdOrder>()
                .eq(OrdOrder::getDelFlag, "0")
                .eq(OrdOrder::getReceivingType,"1")
                .eq(OrdOrder::getDeliveryMode,"1")
                .eq(OrdOrder::getIsUrgentDelivery,"1")
                .between(StringUtils.isNotEmpty(userNumParam.getStartTime())&&StringUtils.isNotEmpty(userNumParam.getEndTime())
                        ,OrdOrder::getCreateTime,userNumParam.getStartTime(),userNumParam.getEndTime()));
        //商家自行配送订单数量
        Integer ziXingNum = ordOrderMapper.selectCount(new LambdaQueryWrapper<OrdOrder>()
                .eq(OrdOrder::getDelFlag, "0")
                .eq(OrdOrder::getReceivingType,"1")
                .eq(OrdOrder::getDeliveryMode,"2")
                .between(StringUtils.isNotEmpty(userNumParam.getStartTime())&&StringUtils.isNotEmpty(userNumParam.getEndTime())
                        ,OrdOrder::getCreateTime,userNumParam.getStartTime(),userNumParam.getEndTime()));
        //用户自提订单数量
        Integer ziTiNum = ordOrderMapper.selectCount(new LambdaQueryWrapper<OrdOrder>()
                .eq(OrdOrder::getDelFlag, "0")
                .eq(OrdOrder::getReceivingType,"2")
                .between(StringUtils.isNotEmpty(userNumParam.getStartTime())&&StringUtils.isNotEmpty(userNumParam.getEndTime())
                        ,OrdOrder::getCreateTime,userNumParam.getStartTime(),userNumParam.getEndTime()));
        //物流订单数
        Integer wuliuNum = ordOrderMapper.selectCount(new LambdaQueryWrapper<OrdOrder>()
                .eq(OrdOrder::getDelFlag, "0")
                .eq(OrdOrder::getReceivingType,"1")
                .eq(OrdOrder::getDeliveryMode,"3")
                .between(StringUtils.isNotEmpty(userNumParam.getStartTime())&&StringUtils.isNotEmpty(userNumParam.getEndTime())
                        ,OrdOrder::getCreateTime,userNumParam.getStartTime(),userNumParam.getEndTime()));
        OrderAnalysis orderAnalysis = new OrderAnalysis(orderTotal,commonNum,jiaJiNum,ziXingNum,ziTiNum);
        orderAnalysis.setWuliuNum(wuliuNum );
        return orderAnalysis;
    }

    /**
     * 订单类型分析饼图
     * @param param
     * @return
     */
    @Override
    public OrderTypeAnaVo getOrderTypeAna(UserNumParam param) {
        OrderTypeAnaVo orderTypeAnaVo = new OrderTypeAnaVo();
        List<OrderTypeAna> otaList=ordOrderMapper.selectOtaList(param);
        //计算总数量
        Integer totalNum = 0;
        for (OrderTypeAna orderTypeAna : otaList) {
            totalNum += orderTypeAna.getTypeNum();
        }
        orderTypeAnaVo.setTotalNum(totalNum);
        orderTypeAnaVo.setOtaList(otaList);
        return orderTypeAnaVo;
    }

    /**
     * 订单分析环形图
     * @param param
     * @return
     */
    @Override
    public OrderTypeAnaVo2 getOrderToroidal(UserNumParam param) {
        OrderTypeAnaVo2 orderTypeAnaVo2 = new OrderTypeAnaVo2();
        List<OrderTypeAna2> otaList=ordOrderMapper.selectAna2(param);
        //计算总数量
        Integer totalNum = 0;
        for (OrderTypeAna2 orderTypeAna : otaList){
            totalNum += orderTypeAna.getNum();
        }
        orderTypeAnaVo2.setTotalNum(totalNum);
        orderTypeAnaVo2.setOtaList(otaList);
        return orderTypeAnaVo2;
    }

    /**
     * 购水用途饼状图
     * @param param
     * @return
     */
    @Override
    public OrderTypeAnaVo2 waterUse(OrderNumParam param) {
        OrderTypeAnaVo2 orderTypeAnaVo2 = new OrderTypeAnaVo2();
        List<OrderTypeAna2> otaList=ordOrderMapper.waterUse(param);
        //计算总数量
        Integer totalNum = 0;
        for (OrderTypeAna2 orderTypeAna : otaList){
            totalNum += orderTypeAna.getNum();
        }
        orderTypeAnaVo2.setTotalNum(totalNum);
        orderTypeAnaVo2.setOtaList(otaList);
        return orderTypeAnaVo2;
    }
    /**
     * 用户下级用户列表
     * @param param
     * @return
     */
    @Override
    public List<UserQuerySubordinateVo> userChildList(UserChildParam param) {
        return userMapper.userChildList(param);
    }
    /**
     * 用户积分发明细
     * @param param
     * @return
     */
    @Override
    public List<IntegralRecordVo> userJfList(UserChildParam param) {
        return userMapper.userJfList(param);
    }

}
